from sqlalchemy import (
    Column, Integer, String, DateTime
)
from sqlalchemy.dialects.postgresql import UUID

import os
import uuid
from datetime import datetime
import hashlib

from app.db import Database

class User(Database.Base):
    __tablename__ = 'users'

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4, unique=True, nullable=False)
    username = Column(String, unique=True, nullable=False, index=True)
    salt = Column(String)
    password_hash = Column(String, nullable=True)  # 密码哈希
    email = Column(String, unique=True)
    phone_number = Column(String, unique=True)
    max_login = Column(Integer, default=5)
    avatar_url = Column(String)
    created_at = Column(DateTime, default=datetime.now)
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)

    def __init__(self, username, password, phone_number=None, email=None, avatar_url=None):
        self.username = username
        self.email = email
        self.phone_number = phone_number
        if password:
            self.salt = os.urandom(16).hex()
            self.password_hash = self.generate_password_hash(password)
        self.avatar_url = avatar_url

    def generate_password_hash(self, password: str):
        password_hash = hashlib.sha256((password + self.salt).encode()).hexdigest()
        return password_hash

Database.create_table_all()